#!/usr/bin/env python

import sys
sys.path.append('/usr/share/pyshared')

from vkontakte import Vkontakte
from askcaptcha import ask_captcha
import os
import subprocess
import sys
import tempfile


query = ' '.join(sys.argv[1:])
if not query:
	print 'usage: vklisten <query>'
	sys.exit(1)


home_dir = os.path.expanduser('~')
home_file = os.path.join(home_dir, '.evlum')

vk = Vkontakte()

if os.path.exists(home_file):
	f = open(home_file, 'r')
	user, pwd = f.read().split(' ')
	f.close()
	
	vk.login(user, pwd)
else:
	
	print 'solve the captcha to register at vkontakte.ru'
	val = vk.register(ask_captcha)
	if val is None:
		sys.exit()
	user, pwd = val

	f = open(home_file, 'w')
	f.write(user+' '+pwd)
	f.close()


found_something = False

m3u = tempfile.NamedTemporaryFile(delete=False, prefix='junk_', suffix=' '+query+'.m3u')
m3u.write("#EXTM3U\n")
print 'searching, hit Ctrl-C to break'
try:
	for page_nr in range(10):
		results = list(vk.search(query, page_nr))
		if not results:
			break
		for entry in results:
			#print entry
			try:
				minutes, seconds = entry['duration'].split(':')
			except ValueError: #TODO: in rare cases there is no duration Vkontakte.search should handle this better...
				seconds = -1
			else:
				seconds = int(seconds) + int(minutes)*60
		
			m3u.write('#EXTINF:'+str(seconds)+','+entry['artist'] + ' - ' + entry['title'] + '\n')
			m3u.write(entry['url'] + '\n')
			found_something = True
			
		print 'got page #'+str(page_nr + 1)
			
except KeyboardInterrupt:
	#print 'interrupted, opening m3u file'
	pass

m3u.close()

if found_something:
	print 'opening:', m3u.name
	subprocess.Popen(['xdg-open', m3u.name]) # needs xdg-util
else:
	print 'no search results found'











